import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import MainLayout from "@/views/common/MainLayout.vue";
import store from "@/store";
import {getMenu} from "@/request/api";
import {listToTree} from "@/util/treeUtil";

Vue.use(VueRouter)


const routes = [
  {
    path: '/',
    name: 'mainLayout',
    redirect: '/home',
    component: MainLayout,
    children:[
      // {
      //   path: '/role',
      //   name: 'role',
      //   component: () => import(/* webpackChunkName: "about" */ '@/views/RoleView.vue')
      // },
      // {
      //   path: '/auth',
      //   name: 'auth',
      //   component: () => import(/* webpackChunkName: "about" */ '@/views/AuthView.vue')
      // }
    ]
  },
  {
    path: '/login',
    name: 'login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../components/LoginView.vue')
  }
]




const router = new VueRouter({
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  let token = window.sessionStorage.getItem("token");
//没有token   访问login(跳转login)
  if (!token && to.path == "/login") {
    next()
    return;
  }

//没有token   访问受限资源  (跳转登录login)
  if (!token && to.path !== "/login") {
    next("/login")
    return;
  }

//有token  访问login  （跳转当前home）
  if (token && to.path == "/login") {
    next("/home")
    return
  }

  // 动态菜单 路由
  if(store.state.menuData.length === 0){
    // 发送异步请求 动态获取菜单
    let {data} = await getMenu()
    let menu = data.map(dt=>{
     if(dt.isMenu===0){
       return {
         // 一级菜单没有路径
         title: dt.title,
         id: dt.id,
         pid: dt.pid,
         icon: dt.icon
       }
     }
     return {
       title: dt.title,
       id: dt.id,
       pid: dt.pid,
       path: dt.path

     }
    })

    // 挂载
    let treeMeu = [{title:'首页',path:'/home',icon:'el-icon-menu'},...listToTree(menu)];

    // 添加到vuex
    store.commit("changeMenuData",treeMeu)

    // 动态路由
    let rts = data.filter(d=>d.isMenu===1).map(dt=>{
      return {
        path: dt.path,
        component: ()=>import('@/views/'+dt.component)
      }
    })

    let newRouter = [{path:'/home',component: () => import(/* webpackChunkName: "about" */ '@/views/HomeView.vue')},
        ...rts,
      {
        path:'/*',
        component: ()=>import('@/views/Page404View.vue')
      }
    ]

    // 加载子路由  遍历
    newRouter.forEach(ntr=>{
      router.addRoute("mainLayout",ntr) // 给mainLayout添加子路由
    })
// 重新走一遍
    next(to.path)
    return
  }



  next();
})


export default router
